package com.gzc.just.play.last.war.centralserver.user.controller;

import com.gzc.just.play.last.war.centralserver.user.dto.UserLoginRequest;
import com.gzc.just.play.last.war.centralserver.user.dto.UserRegisterRequest;
import com.gzc.just.play.last.war.centralserver.user.model.User;
import com.gzc.just.play.last.war.centralserver.service.UserStatusService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户管理控制器
 */
@RestController
@RequestMapping("/api/user")
@CrossOrigin(origins = "*", maxAge = 3600)
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    
    @Autowired
    private UserStatusService userService;
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody UserLoginRequest request) {
        logger.info("User login attempt: {}", request.getUsername());
        try {
            Map<String, Object> result = userService.login(request);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("Login error", e);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "登录失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }
    
    /**
     * 用户注册
     */
    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> register(@RequestBody UserRegisterRequest request) {
        logger.info("User registration attempt: {}", request.getUsername());
        try {
            Map<String, Object> result = userService.register(request);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("Registration error", e);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "注册失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }
    
    /**
     * 用户登出
     */
    @PostMapping("/logout")
    public ResponseEntity<Map<String, Object>> logout(@RequestParam Long userId) {
        logger.info("User logout: {}", userId);
        try {
            userService.logout(userId);
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "登出成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("Logout error", e);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "登出失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }
    
    /**
     * 获取用户信息
     */
    @GetMapping("/{userId}")
    public ResponseEntity<Map<String, Object>> getUserInfo(@PathVariable Long userId) {
        try {
            User user = userService.getUserInfoObject(userId);
            Map<String, Object> result = new HashMap<>();
            if (user != null) {
                result.put("success", true);
                result.put("user", user);
            } else {
                result.put("success", false);
                result.put("message", "用户不存在");
            }
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("Get user info error", e);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "获取用户信息失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }
    
    /**
     * 更新用户信息
     */
    @PutMapping("/{userId}")
    public ResponseEntity<Map<String, Object>> updateUserInfo(@PathVariable Long userId, @RequestBody User user) {
        try {
            user.setUserId(userId);
            User updatedUser = userService.updateUserInfo(user);
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("user", updatedUser);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("Update user info error", e);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "更新用户信息失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }
    
    /**
     * 增加用户经验
     */
    @PostMapping("/{userId}/exp")
    public ResponseEntity<Map<String, Object>> addExp(@PathVariable Long userId, @RequestParam long amount) {
        try {
            userService.addUserExp(userId, amount);
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "经验增加成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("Add exp error", e);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "增加经验失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }
    
    /**
     * 增加用户金币
     */
    @PostMapping("/{userId}/gold")
    public ResponseEntity<Map<String, Object>> addGold(@PathVariable Long userId, @RequestParam long amount) {
        try {
            userService.addUserGold(userId, amount);
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "金币增加成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("Add gold error", e);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "增加金币失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }
    
    /**
     * 增加用户钻石
     */
    @PostMapping("/{userId}/gems")
    public ResponseEntity<Map<String, Object>> addGems(@PathVariable Long userId, @RequestParam long amount) {
        try {
            userService.addUserGems(userId, amount);
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "钻石增加成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("Add gems error", e);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "增加钻石失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }
    
    /**
     * 恢复用户体力
     */
    @PostMapping("/{userId}/power/recover")
    public ResponseEntity<Map<String, Object>> recoverPower(@PathVariable Long userId, @RequestParam int amount) {
        try {
            userService.recoverUserPower(userId, amount);
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "体力恢复成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("Recover power error", e);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "恢复体力失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }
    
    /**
     * 消耗用户体力
     */
    @PostMapping("/{userId}/power/consume")
    public ResponseEntity<Map<String, Object>> consumePower(@PathVariable Long userId, @RequestParam int amount) {
        try {
            boolean success = userService.consumeUserPower(userId, amount);
            Map<String, Object> result = new HashMap<>();
            result.put("success", success);
            if (success) {
                result.put("message", "体力消耗成功");
            } else {
                result.put("message", "体力不足");
            }
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("Consume power error", e);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "消耗体力失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }
    
    /**
     * 获取排名前N的玩家
     */
    @GetMapping("/ranking/{limit}")
    public ResponseEntity<Map<String, Object>> getTopPlayers(@PathVariable int limit) {
        try {
            List<User> topPlayers = userService.getTopPlayers(Math.min(limit, 100));
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("players", topPlayers);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("Get top players error", e);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "获取排名失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }
    
    /**
     * 获取在线用户数
     */
    @GetMapping("/online/count")
    public ResponseEntity<Map<String, Object>> getOnlineUserCount() {
        try {
            long count = userService.getOnlineUserCount();
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("onlineUserCount", count);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("Get online user count error", e);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "获取在线用户数失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }
    
    /**
     * 检查用户是否在线
     */
    @GetMapping("/{userId}/online")
    public ResponseEntity<Map<String, Object>> isUserOnline(@PathVariable Long userId) {
        try {
            boolean isOnline = userService.isUserOnline(userId);
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("isOnline", isOnline);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("Check user online error", e);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "检查用户在线状态失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }
}
